﻿using iMES.Core.BaseProvider;
using iMES.Core.Enums;
using iMES.Core.Extensions;
using iMES.Core.Utilities;
using iMES.Custom.IRepositories;
using iMES.Custom.Services;
using iMES.Entity.DomainModels;
using iMES.Inventory.IRepositories;
using iMES.Inventory.Repositories;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace iMES.Inventory.Services
{
    public partial class View_InventoryStoreServices
    {
        private readonly IHttpContextAccessor _httpContextAccessor;
        private readonly IView_InventoryStoreRepositoies view_InventoryStoreRepositoies;
        private readonly IBase_NumberRuleRepository _numberRuleRepository;//自定义编码规则访问数据库
        private  readonly IBase_ProductRepository _productRepository;
        [ActivatorUtilitiesConstructor]
        public View_InventoryStoreServices(
            IView_InventoryStoreRepositoies dbRepository,
            IHttpContextAccessor httpContextAccessor,
            IBase_ProductRepository productRepository,
            IBase_NumberRuleRepository numberRuleRepository)
        : base(dbRepository)
        {
            _httpContextAccessor = httpContextAccessor;
            view_InventoryStoreRepositoies = dbRepository;
            _numberRuleRepository = numberRuleRepository;
            _productRepository = productRepository;
        }

        WebResponseContent WebResponseContent = new WebResponseContent();

        public override WebResponseContent Add(SaveModel saveDataModel)
        {
            AddOnExecuting = (Inventory_Store entiyt, object list) =>
            {
                if (string.IsNullOrWhiteSpace(entiyt.WareHouseBillCode))
                    entiyt.WareHouseBillCode = GetWareHouseBillCode();
                return WebResponseContent.OK();
            };
            return base.Add(saveDataModel);
        }
        public override object GetDetailPage(PageDataOptions pageData)
        {
            var query = View_StoreDetailsRepositories.Instance.IQueryablePage<Invent_StoreDetails>(
                 pageData.Page,
                 pageData.Rows,
                 out int count,
                 x => x.WareHouseBill_Id == pageData.Value.GetInt(),
                  orderBy: x => new Dictionary<object, QueryOrderBy>() { { x.CreateDate, QueryOrderBy.Desc } }
                );
            PageGridData<Invent_StoreDetails> detailGrid = new PageGridData<Invent_StoreDetails>();
            detailGrid.rows = query.ToList();
            detailGrid.total = count;
            //获取当前库存数量
            List<Base_Product> storeList = Base_ProductService.GetStoreNumber();
            for (int i = 0; i < detailGrid.rows.Count; i++)
            {
                if (storeList.Exists(x => x.Product_Id == detailGrid.rows[i].Product_Id))
                {
                    detailGrid.rows[i].InventoryQty = storeList.Find(x => x.Product_Id == detailGrid.rows[i].Product_Id).InventoryQty;
                }
                else
                {
                    detailGrid.rows[i].InventoryQty = 0;
                }
            }
            return detailGrid;
        }

        /// <summary>
        /// 自动生成工序编号
        /// </summary>
        /// <returns></returns>
        public string GetWareHouseBillCode()
        {
            DateTime dateNow = (DateTime)DateTime.Now.ToString("yyyy-MM-dd").GetDateTime();
            //查询当天最新的订单号
            string defectItemCode = repository.FindAsIQueryable(x => x.CreateDate > dateNow && x.WareHouseBillCode.Length > 8)
                .OrderByDescending(x => x.WareHouseBillCode)
                .Select(s => s.WareHouseBillCode)
                .FirstOrDefault();
            Base_NumberRule numberRule = _numberRuleRepository.FindAsIQueryable(x => x.FormCode == "InStoreForm")
                .OrderByDescending(x => x.CreateDate)
                .FirstOrDefault();
            if (numberRule != null)
            {
                string rule = numberRule.Prefix + DateTime.Now.ToString(numberRule.SubmitTime.Replace("hh", "HH"));
                if (string.IsNullOrEmpty(defectItemCode))
                {
                    rule += "1".PadLeft(numberRule.SerialNumber, '0');
                }
                else
                {
                    rule += (defectItemCode.Substring(defectItemCode.Length - numberRule.SerialNumber).GetInt() + 1).ToString("0".PadLeft(numberRule.SerialNumber, '0'));
                }
                return rule;
            }
            else //如果自定义序号配置项不存在，则使用日期生成
            {
                return DateTime.Now.ToString("yyyyMMddHHmmssffff");
            }
        }
    }
    
}
